package com.huibao.hulibao.fragment;

import android.Manifest;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.BaseColumns;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.apkfuns.logutils.LogUtils;
import com.example.zhouwei.library.CustomPopWindow;
import com.huibao.hulibao.R;
import com.huibao.hulibao.activity.BigPicActivity;
import com.huibao.hulibao.activity.CheckActivity;
import com.huibao.hulibao.activity.LoginActivity;
import com.huibao.hulibao.adapter.CheckLvAdapter;
import com.huibao.hulibao.adapter.PhotoGvAdapter;
import com.huibao.hulibao.constant.GlobalConstants;
import com.huibao.hulibao.entity.CheckEntity;
import com.huibao.hulibao.entity.LoginEntity;
import com.huibao.hulibao.entity.ResultEntity;
import com.huibao.hulibao.utils.CropImageUtils;
import com.huibao.hulibao.utils.PreUtils;
import com.huibao.hulibao.utils.T;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

/**
 * Created by lizhaoyong on 2018/5/7.
 */
public class LocationFragmentView extends Fragment {
    private Unbinder unbinder;

    private Context context;
    @BindView(R.id.gv_photo)
    GridView gv_photo;
    @BindView(R.id.ll_location)
    LinearLayout ll_location;
    @BindView(R.id.lv_check)
    ListView lv_check;
    @BindView(R.id.srl_check)
    SmartRefreshLayout srl_check;
    @BindView(R.id.iv_check)
    ImageView iv_check;
    @BindView(R.id.et_check)
    EditText et_check;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.tv_title)
    TextView tv_title;

    // 图片存放集合
    private ArrayList<Bitmap> al_Bitmaps;
    private ArrayList<String> al_imgs;
    // 选中图片的下标
    private int position = 0;
    protected static Uri tempUri;
    // 图片的选中状态
    protected static final int CHOOSE_PICTURE = 0;
    protected static final int TAKE_PICTURE = 1;
    private static final int CROP_SMALL_PICTURE = 2;

    // 弹出拍照取照片的POPWINDOW
    private PopupWindow pop_photo;
    private LinearLayout ll_popwindow_photo;

    public CheckActivity mainActivity;
    public LoginEntity le;

    private CropImageUtils cropImageUtils;


    // 弹出选中照片的popwindow
    private CustomPopWindow popWindow;


    // 三张图片的数组地址
    public String[] arr_pic = {"", "", ""};

    @OnClick({R.id.iv_back, R.id.tv_back})
    public void back() {
        mainActivity.finish();
    }

    @OnClick(R.id.iv_check)
    public void check() {
        checkDataToServer();
    }

//    public void showPopWindow(String url) {
//        popWindow = new CustomPopWindow.PopupWindowBuilder(mainActivity)
//                .setView(R.layout.popwindow_show_pic)
//                .setFocusable(true)
//                .size(800, 800)
//                .setOutsideTouchable(true)
//                // pop消失监听
//                .setOnDissmissListener(new PopupWindow.OnDismissListener() {
//                    @Override
//                    public void onDismiss() {
//
//                    }
//                })
//                .create();
//        ImageView iv = (ImageView) popWindow.getPopupWindow().getContentView().findViewById(R.id.iv_pic);
//        Glide.with(mainActivity).load(url).into(iv);
//        popWindow.showAsDropDown(tv_title, 300, 100);
//    }


    public void enterBigPicActivity(String url) {
        Intent intent = new Intent(mainActivity, BigPicActivity.class);
        intent.putExtra("pic", url);
        startActivity(intent);

    }


    // 定位
    @OnClick(R.id.tv_address)
    public void location() {
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            // 没有权限，申请权限。
            // 请求开启相机权限
            PermissionGen.needPermission(LocationFragmentView.this, 106,
                    new String[]{
                            Manifest.permission.ACCESS_FINE_LOCATION}
            );
        } else {
            mLocationClient.startLocation();
        }
    }

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    private AMapLocationClientOption mLocationOption;
    public LocationFragmentView lfv;


    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    mLocationClient.stopLocation();
                    //可在其中解析amapLocation获取相应内容。
                    LogUtils.d("地址 = " + aMapLocation.getAddress());
                    tv_address.setText(aMapLocation.getAddress());
                    // tv_address.setText(address);
                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    LogUtils.d("location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                }
            }
        }
    };


    // 向服务器提交数据
    public void checkDataToServer() {
        RequestParams params = new RequestParams(GlobalConstants.URL);
        params.setCacheMaxAge(0);
        mainActivity.showDialog();
        JSONObject object = new JSONObject();
        try {
            if (al_imgs.size() == 0) {
                object.put("imgs", "");
            } else {
                if (al_imgs.size() == 1) {
                    object.put("imgs", al_imgs.get(0).replace(":", "@@"));
                } else {
                    if (al_imgs.size() == 2) {
                        StringBuffer sb = new StringBuffer();
                        sb.append(al_imgs.get(0).replace(":", "@@")).append(";").append(al_imgs.get(1).replace(":", "@@"));
                        object.put("imgs", sb.toString());
                    } else if (al_imgs.size() == 3) {
                        StringBuffer sb = new StringBuffer();
                        sb.append(al_imgs.get(0).replace(":", "@@")).append(";").append(al_imgs.get(1).replace(":", "@@")).append(";").append(al_imgs.get(2).replace(":", "@@"));
                        object.put("imgs", sb.toString());
                    }
                }
            }
            object.put("info", et_check.getText().toString());
            object.put("loc", tv_address.getText().toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.addBodyParameter("q", le.Message.Session + GlobalConstants.URL_POS_CHECK_DATA + object.toString());
        // LogUtils.d("params = " + params);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                mainActivity.closeDialog();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    LogUtils.d("result = " + jsonObject.toString());
                    ResultEntity re = GlobalConstants.gson.fromJson(jsonObject.toString(), ResultEntity.class);
                    if (re.State.equals(GlobalConstants.SUCCESS_CODE)) {
                        getCheckDataFromServer();
                        et_check.setText("");
                        T.show(context, "Check 成功", 0);
                    } else {
                        LogUtils.d("messgae = " + re.Message);
                        T.show(context, re.Message, 0);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mainActivity.closeDialog();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                mainActivity.closeDialog();
            }

            @Override
            public void onFinished() {
                mainActivity.closeDialog();
            }
        });
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_location, null);
        unbinder = ButterKnife.bind(this, v);
        context = getActivity();
        mainActivity = (CheckActivity) getActivity();
        // T.show(context,"length = " + arr_pic.length,0);
        //初始化定位
        mLocationClient = new AMapLocationClient(mainActivity);
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        mLocationOption = new AMapLocationClientOption();
        //设置为高精度定位模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
        mLocationOption.setOnceLocation(true);
        // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
        // 在定位结束后，在合适的生命周期调用onDestroy()方法
        // LogUtils.d("sha1 = " + MyUtils.sHA1(getApplicationContext()));
        // 点击外部收起软键盘
        v.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                InputMethodManager manager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    if (getActivity().getCurrentFocus() != null && getActivity().getCurrentFocus().getWindowToken() != null) {
                        manager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
                return false;
            }
        });

        initPopWindowPhoto();
        al_Bitmaps = new ArrayList<Bitmap>();
        al_imgs = new ArrayList<String>();
        //初始化裁剪工具
        //cropImageUtils = new CropImageUtils(getActivity());

        gv_photo.setSelector(new ColorDrawable(Color.TRANSPARENT));
        gv_photo.setAdapter(new PhotoGvAdapter(al_Bitmaps, context, al_imgs, 3));
        gv_photo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                position = i;
                ll_popwindow_photo.startAnimation(AnimationUtils.loadAnimation(
                        context, R.anim.activity_translate_in));
                pop_photo.showAtLocation(ll_location, Gravity.BOTTOM, 0, 0);
                closeKeybord();
            }
        });

        getCheckDataFromServer();
        //下拉刷新
        srl_check.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getCheckDataFromServer();
            }
        });
        return v;
    }


    @Override
    public void onDestroy() {
        mLocationClient.stopLocation();
        super.onDestroy();
    }

    // 获取check数据
    public void getCheckDataFromServer() {
        final CheckActivity mainActivity = (CheckActivity) getActivity();
        le = (LoginEntity) PreUtils.getObject(context, "LoginEntity");
        if (le == null) {
            Intent intent = new Intent(context, LoginActivity.class);
            startActivity(intent);
            getActivity().finish();
        } else {
            RequestParams params = new RequestParams(GlobalConstants.URL);
            params.setCacheMaxAge(0);
            mainActivity.showDialog();
//        JSONObject object = new JSONObject();
//        try {
//            object.put("type", type);
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }

            params.addBodyParameter("q", le.Message.Session + GlobalConstants.URL_CHECK_STEAM + "-");
            // LogUtils.d("params = " + params);
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    srl_check.finishRefresh();
                    mainActivity.closeDialog();
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(result);
                        // 登录超时
                        if (jsonObject.toString().contains("\"State\"" + ":" + "\"" + GlobalConstants.LOGIN_TIME_OUT + "\"")) {
                            // 退出登录
                            PreUtils.saveObject(context, "LoginEntity", null);
                            Intent intent = new Intent(context, LoginActivity.class);
                            startActivity(intent);
                            getActivity().finish();
                            return;
                        }
                        // LogUtils.d("result = " + jsonObject.toString());
                        CheckEntity ce = GlobalConstants.gson.fromJson(jsonObject.toString(), CheckEntity.class);
                        lv_check.setAdapter(new CheckLvAdapter(ce.Message, context, LocationFragmentView.this));


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    srl_check.finishRefresh();
                    mainActivity.closeDialog();
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    srl_check.finishRefresh();
                    mainActivity.closeDialog();
                }

                @Override
                public void onFinished() {
                    srl_check.finishRefresh();
                    mainActivity.closeDialog();
                }
            });
        }
    }


    private void closeKeybord() {
        View view = getActivity().getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputmanger = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }


    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) { // 如果返回码是可以用的
            switch (requestCode) {
                // 拍照返回
                case TAKE_PICTURE:
                    // 7.0
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        setImageToView(data);
                    } else {
                        startPhotoZoom(tempUri); // 开始对图片进行裁剪处理
                    }
                    break;
                // 相册返回
                case CHOOSE_PICTURE:
                    // 7.0
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        try {
                            Uri uri = data.getData();
                            LogUtils.d("uri = " + uri);
                            if (String.valueOf(uri).substring(0, 4).equals("file")) {
                                // Log.i(TAG, "uri = " + uri);
                                File myFile = new File(uri.getPath());
                                Uri selectedImage = getImageContentUri(
                                        mainActivity, myFile);
                                // Log.i(TAG, "selectedImage = " + selectedImage);
                                String realpath = getRealPathFromUri(
                                        mainActivity, selectedImage);
                                // Log.i(TAG, "realpath = " + realpath);
//                                PreUtils.setParam(mainActivity,
//                                        GlobalContants.PHOTO_PATH, realpath);
                                BitmapFactory.Options options = new BitmapFactory.Options();
                                options.inSampleSize = 6;// 图片宽高都为原来的二分之一，即图片为原来的四分之一
                                Bitmap bitmap = BitmapFactory
                                        .decodeFile(realpath, options);
                                if (position < al_Bitmaps.size()) {
                                    if (al_Bitmaps.get(position) != null) {
                                        al_Bitmaps.remove(position);
                                        al_imgs.remove(position);
                                        al_Bitmaps.add(position, bitmap);
                                    } else {
                                        al_Bitmaps.add(position, bitmap);
                                    }
                                } else {
                                    al_Bitmaps.add(position, bitmap);
                                }
                                // bitmap保存到本地
                                saveBitmapFile(bitmap);
                                // 提交图片到服务器
                                postPicToServer();
                                gv_photo.setAdapter(new PhotoGvAdapter(
                                        al_Bitmaps, context, al_imgs, 3));
                            } else if (String.valueOf(uri).substring(0, 7)
                                    .equals("content")) {
                                String imagePath = null;
                                Log.d("uri=intent.getData :", "" + uri);
                                if (DocumentsContract.isDocumentUri(mainActivity, uri)) {
                                    String docId = DocumentsContract.getDocumentId(uri);        //数据表里指定的行
//                                    Log.d("getDocumentId(uri) :", "" + docId);
//                                    Log.d("uri.getAuthority() :", "" + uri.getAuthority());
                                    if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                                        String id = docId.split(":")[1];
                                        String selection = MediaStore.Images.Media._ID + "=" + id;
                                        imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
                                    } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                                        Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                                        imagePath = getImagePath(contentUri, null);
                                    }

                                } else if ("content".equalsIgnoreCase(uri.getScheme())) {
                                    imagePath = getImagePath(uri, null);
                                }

                                BitmapFactory.Options options = new BitmapFactory.Options();
                                options.inSampleSize = 10;// 图片宽高都为原来的十分之一，即图片为原来的四分之一
                                Bitmap bitmap = BitmapFactory.decodeFile(imagePath,
                                        options);
                                if (position < al_Bitmaps.size()) {
                                    if (al_Bitmaps.get(position) != null) {
                                        al_Bitmaps.remove(position);
                                        al_imgs.remove(position);
                                        al_Bitmaps.add(position, bitmap);
                                    } else {
                                        al_Bitmaps.add(position, bitmap);
                                    }
                                } else {
                                    al_Bitmaps.add(position, bitmap);
                                }
                                // bitmap保存到本地
                                saveBitmapFile(bitmap);
                                // 提交图片到服务器
                                postPicToServer();
                                gv_photo.setAdapter(new PhotoGvAdapter(
                                        al_Bitmaps, context, al_imgs, 3));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        startPhotoZoom(data.getData()); // 开始对图片进行裁剪处理
                    }
                    break;
                // 7.0一下的返回处理
                case CROP_SMALL_PICTURE:
                    if (data != null) {
                        setImageToView(data); // 让刚才选择裁剪得到的图片显示在界面上
                    }
                    break;
            }
        }
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        Cursor cursor = mainActivity.getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    public static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{BaseColumns._ID}, MediaStore.MediaColumns.DATA + "=? ",
                new String[]{filePath}, null);

        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(BaseColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.MediaColumns.DATA, filePath);
                return context.getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

    public String getRealPathFromUri(Context context, Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = {MediaStore.MediaColumns.DATA};
            cursor = context.getContentResolver().query(contentUri, proj, null,
                    null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    // 设置图片
    private void setImageToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap bitmap = extras.getParcelable("data");
            // 添加图片的逻辑
            if (position < al_Bitmaps.size()) {
                if (al_Bitmaps.get(position) != null) {
                    al_Bitmaps.remove(position);
                    al_imgs.remove(position);
                    al_Bitmaps.add(position, bitmap);
                } else {
                    al_Bitmaps.add(position, bitmap);
                }
            } else {
                al_Bitmaps.add(position, bitmap);
            }
            // bitmap保存到本地
            saveBitmapFile(bitmap);
            // 提交图片到服务器
            postPicToServer();
            gv_photo.setAdapter(new PhotoGvAdapter(
                    al_Bitmaps, context, al_imgs, 3));
        }
    }

    public void saveBitmapFile(Bitmap bitmap) {
        // 创建文件夹
        File file = null;
        try {
            file = new File(Environment.getExternalStorageDirectory()
                    + File.separator + "hulibao_check" + File.separator);
            // 如果文件夹不存在就创建
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        File f = new File(Environment.getExternalStorageDirectory()
                + File.separator + "hulibao_check" + File.separator + "check_pic.jpg");
        try {
            FileOutputStream out = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static byte[] readStream(String imagepath) throws Exception {
        FileInputStream fs = new FileInputStream(imagepath);
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while (-1 != (len = fs.read(buffer))) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        fs.close();
        return outStream.toByteArray();
    }

    // 提交单个图片到服务器
    public void postPicToServer() {
        mainActivity.showDialog();
        RequestParams params = new RequestParams(GlobalConstants.URL_PIC_CACHE);
        params.setCacheMaxAge(0);
        params.setMultipart(true);
        params.addBodyParameter("sign", "ISVIP_URYRHEUYRYRTHYEY8987656");
        params.addBodyParameter("type", "png");
        String path = Environment.getExternalStorageDirectory()
                + File.separator + "hulibao_check" + File.separator + "check_pic.jpg";
        try {
            params.addBodyParameter("file", readStream(path), "image/jpg");
        } catch (Exception e) {
            e.printStackTrace();
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                al_imgs.add(position, result);
                LogUtils.d("result = " + result);
                mainActivity.closeDialog();
                // arr_pic[position] = result;
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mainActivity.closeDialog();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                mainActivity.closeDialog();
            }

            @Override
            public void onFinished() {
                mainActivity.closeDialog();
            }
        });


    }


    /**
     * 裁剪图片方法实现
     */
    protected void startPhotoZoom(Uri uri) {
        if (uri == null) {
            return;
        }
        tempUri = uri;
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 500);
        intent.putExtra("outputY", 500);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_SMALL_PICTURE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }


    @PermissionSuccess(requestCode = 106)
    public void doLocation() {
        mLocationClient.startLocation();
    }

    @PermissionFail(requestCode = 106)
    public void doFailLocation() {
        T.show(getActivity(), "定位权限打开失败！", 0);
    }

    @PermissionSuccess(requestCode = 107)
    public void doOpenLocationPhoto() {
        Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
        openAlbumIntent.setType("image/*");
        getActivity().overridePendingTransition(R.anim.activity_translate_in,
                R.anim.activity_translate_out);
        startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
        pop_photo.dismiss();
        ll_popwindow_photo.clearAnimation();
    }

    @PermissionFail(requestCode = 107)
    public void doFailLocationPhoto() {
        T.show(getActivity(), "读取本地图片权限被拒绝！", 0);
    }


    @PermissionSuccess(requestCode = 105)
    public void doSomething() {
        T.show(getActivity(), "相机权限已开启", 0);
        // cropImageUtils.takePhoto();
        Intent openCameraIntent = new Intent(
                MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

        } else {
            tempUri = Uri.fromFile(new File(Environment
                    .getExternalStorageDirectory(), "image.jpg"));
            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
        }
        startActivityForResult(openCameraIntent, TAKE_PICTURE);
        pop_photo.dismiss();
        ll_popwindow_photo.clearAnimation();
    }

    @PermissionFail(requestCode = 105)
    public void doFailSomething() {
        T.show(getActivity(), "相机权限打开失败！", 0);
    }


    public void initPopWindowPhoto() {
        pop_photo = new PopupWindow(context);
        View view = getActivity().getLayoutInflater().inflate(R.layout.popwindow_select_photo, null);
        ll_popwindow_photo = (LinearLayout) view.findViewById(R.id.ll_popwindow_photo);

        pop_photo.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        pop_photo.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        pop_photo.setBackgroundDrawable(new ColorDrawable(0xc0cccccc));
        pop_photo.setFocusable(true);
        pop_photo.setOutsideTouchable(true);
        pop_photo.setContentView(view);

        RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent);
        Button bt1 = (Button) view.findViewById(R.id.item_popupwindows_camera);
        Button bt2 = (Button) view.findViewById(R.id.item_popupwindows_Photo);

        // 不显示相册获取
        View v_div = view.findViewById(R.id.v_div);
        bt2.setVisibility(View.GONE);
        v_div.setVisibility(View.GONE);
        Button bt3 = (Button) view.findViewById(R.id.item_popupwindows_cancel);
        parent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop_photo.dismiss();
                ll_popwindow_photo.clearAnimation();
            }
        });

        // 拍照
        bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 请求开启拍照权限和读写权限
                if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    // 请求开启相机权限
                    PermissionGen.needPermission(LocationFragmentView.this, 105,
                            new String[]{
                                    Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}

                    );
                } else {
                    Intent openCameraIntent = new Intent(
                            MediaStore.ACTION_IMAGE_CAPTURE);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

                    } else {
                        tempUri = Uri.fromFile(new File(Environment
                                .getExternalStorageDirectory(), "image.jpg"));
                        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
                    }
                    startActivityForResult(openCameraIntent, TAKE_PICTURE);
                    pop_photo.dismiss();
                    ll_popwindow_photo.clearAnimation();
                }
            }
        });

        // 相册获取
        bt2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 读取本地相册权限
                if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    // 请求开启本地相册权限
                    PermissionGen.needPermission(LocationFragmentView.this, 107,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}
                    );
                } else {
                    // cropImageUtils.openAlbum();
                    Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
                    openAlbumIntent.setType("image/*");
                    getActivity().overridePendingTransition(R.anim.activity_translate_in,
                            R.anim.activity_translate_out);
                    startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
                    pop_photo.dismiss();
                    ll_popwindow_photo.clearAnimation();
                }
            }
        });
        bt3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop_photo.dismiss();
                ll_popwindow_photo.clearAnimation();
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
